package com.fy56.platform.logistics.service.impl;


import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fy56.platform.logistics.common.BaseEntity;
import com.fy56.platform.logistics.common.Page;
import com.fy56.platform.logistics.common.ResultModel;
import com.fy56.platform.logistics.common.ResultStatus;
import com.fy56.platform.logistics.mapper.WithDrawMoneyMainMapper;
import com.fy56.platform.logistics.model.Company;
import com.fy56.platform.logistics.model.WithDrawMoneyMain;
import com.fy56.platform.logistics.model.WithdrawMoney;
import com.fy56.platform.logistics.service.wx.ICompanyInfoService;
import com.fy56.platform.logistics.service.wx.ILogisticsSlaveBasisService;
import com.fy56.platform.logistics.service.wx.WithdrawMoneyService;
import com.fy56.platform.logistics.utils.*;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.fy56.platform.logistics.utils.HttpUtil.setHeader;


/**
 * @author by Edwin Yang on 2018/2/26 0026.
 */
@Service
public class WithdrawMoneyServiceImpl implements WithdrawMoneyService {

    @Autowired
    ICompanyInfoService iCompanyInfoService;

    @Autowired
    ILogisticsSlaveBasisService iLogisticsBasisService;

    @Autowired
    WithDrawMoneyMainMapper withDrawMoneyMainMapper;


    @Override
    public WithdrawMoney selectByPrimaryKey(Long id) {
        return null;
    }

    @Override
    public WithdrawMoney get(WithdrawMoney entity) {
        return null;
    }

    @Override
    public ResultModel insert(WithdrawMoney entity) {
        return null;
    }

    @Override
    public ResultModel insertSelective(WithdrawMoney entity) {
        return null;
    }

    @Override
    public ResultModel update(WithdrawMoney entity) {
        return null;
    }

    @Override
    public ResultModel updateSelective(WithdrawMoney entity) {
        return null;
    }

    @Override
    public ResultModel delete(Long id) {
        return null;
    }

    @Override
    public ResultModel delete(WithdrawMoney entity) {
        return null;
    }

    @Override
    public List<WithdrawMoney> findList(WithdrawMoney withdrawMoney) {
        return null;
    }

    /**
     * 根据tenant
     */
    @Override
    public ResultModel validateOrder(String tenant,List<WithdrawMoney> withdrawMoneyLst ,String mobile) {
        String postResult = "";
        Map<String,Object> params = new HashMap<>();
        Map<String,String> paramsMap = new HashMap<>();
        params.put("telphone" , mobile);
        params.put("financialCode" ,tenant);
        params.put("data",withdrawMoneyLst);
        String postStr = JSON.toJSONString(params);
        paramsMap.put("param",postStr);
        List<WithdrawMoney> result = null;
        List<WithdrawMoney> list = Lists.newArrayList();
        //如果是F6系统，则帐套名称和组织代码必须传
        Company company = iCompanyInfoService.getCompanyByCode(tenant);
        String url = company.getUrl()+"/withdrawAudit/checkAppWithdrawData";
        if(StringUtil.isNotEmpty(company.getF6AccountSet()) && StringUtil.isNotEmpty(company.getF6OrganizationCode())){
            url += "?accountName=" + company.getF6AccountSet() + "&organizationCode=" + company.getF6OrganizationCode();
        }
        //未通过验证的信息
        String msg = "";
        try {
            postResult = HttpUtil.post(url,paramsMap);
            if(StringUtil.isNotEmpty(postResult) && "SUCCESS".equals(JSON.parseObject(postResult).getString("msg"))){
                result = JSON.parseObject(postResult).getJSONArray("content").toJavaList(WithdrawMoney.class);
                if(result != null && result.size() > 0){
                    for(WithdrawMoney model : result){
                        if(StringUtil.isNotEmpty(model.getRemark())){
                            if(msg.length() == 0){
                                msg += "票号：" + model.getOrderNo() + " " + model.getRemark();
                            }else{
                                msg += "\n票号：" + model.getOrderNo() + " " + model.getRemark();
                            }
                        }else{
                            model.setFinancialCode(tenant);
                            list.add(model);
                        }
                    }
                }
            }else{
                return new ResultModel(ResultStatus.SERVER_ERROR);
            }
        } catch (Exception e) {
            return new ResultModel(ResultStatus.SERVER_ERROR);
        }
        return new ResultModel(200,msg,list);
    }

    @Override
    public ResultModel addWithdraw(List<WithdrawMoney> withdrawMoneyLst,String code) throws Exception {
        String withDraw = IdWorkerTools.getInstance().getId();
        Map<String, String> postParams = Maps.newHashMap();
        for(int i =0; i<withdrawMoneyLst.size(); i++){
            withdrawMoneyLst.get(i).setWithdrawNo(withDraw);
        }
        String str = JSON.toJSONString(withdrawMoneyLst);
        postParams.put("param",str);
        //如果是F6系统，则帐套名称和组织代码必须传
        Company company = iCompanyInfoService.getCompanyByCode(code);
        String url = company.getUrl() + "/withdrawAudit/save";
        if(StringUtil.isNotEmpty(company.getF6AccountSet()) && StringUtil.isNotEmpty(company.getF6OrganizationCode())){
            url += "?accountName=" + company.getF6AccountSet() + "&organizationCode=" + company.getF6OrganizationCode();
        }
        //String postResult = HttpUtil.post(url,postParams);
        String postResult = HttpClientUtils.post( url+"&param="+ str, null, setHeader(), 20000, 20000);
        ResultModel model = JSON.parseObject(postResult,ResultModel.class);
        String failMes = "";
        if(200 == model.getCode()){
            if("SUCCESS".equals(model.getMsg())){
                Double totalDeliveryCollection = 0.0;
                String withDrawNo = "";
                String bankAccount = "";
                String bankName="";
                String bankCardNo="";
                String idCardNo="";
                String accountMobile="";
                String vipNo="";
                List<WithdrawMoney> result = JSON.parseArray(JSON.toJSONString(model.getContent()),WithdrawMoney.class);
                WithdrawMoney withdrawMoney = null;
                for(int i = 0; i< result.size();i++){
                    withdrawMoney = result.get(i);
                    if("成功".equals(withdrawMoney.getRemark())){
                        totalDeliveryCollection += withdrawMoney.getDeliveryCollection();
                        withDrawNo = withdrawMoney.getWithdrawNo();
                        bankAccount = withdrawMoney.getAccountName();
                        bankName = withdrawMoney.getBankName();
                        bankCardNo = withdrawMoney.getBankAccount();
                        idCardNo = withdrawMoney.getIdCard();
                        accountMobile = withdrawMoney.getTelphone();
                        vipNo = withdrawMoney.getVipNo();
                    }else{
                        failMes += "票号["+withdrawMoney.getOrderNo()+"]" + withdrawMoney.getRemark();
                    }
                }
                if(StringUtil.isNotEmpty(withDrawNo)){
                    WithDrawMoneyMain record = new WithDrawMoneyMain();
                    record.setWithDrawNo(withDrawNo);
                    record.setDeliveryCollection(totalDeliveryCollection.toString());
                    record.setCreateTime(DateUtil.getNowTime());
                    record.setOrderSum(result.size());
                    record.setBankAccount(bankAccount);
                    record.setBankCardNo(bankCardNo);
                    record.setAccountMobile(accountMobile);
                    record.setIdCardNo(idCardNo);
                    record.setBankName(bankName);
                    record.setVipNo(vipNo);
                    record.setCode(code);
                    withDrawMoneyMainMapper.insert(record);
                    return ResultModel.ok(result);
                }
            }else{
                return ResultModel.error(model.getMsg());
            }
        }
        return ResultModel.error(StringUtil.isNotEmpty(failMes) ? failMes : "提审取款记录");
    }

    @Override
    public Page<Map<String, Object>> findWithdrawLocal(String mobile,Integer pageCount,Integer pageIndex) {
        BaseEntity entity = new BaseEntity();
        entity.setTable_(" withdraw_money_main w left join company c on c.code = w.code ");
        entity.setColumn_(" w.with_draw_no as withDrawNo, w.create_time as createDate," +
                "w.delivery_collection as deliveryCollection, w.order_sum as orderSum,w.bank_name as bankName," +
                "w.bank_card_no as bankCardNo,c.name as tenantName ");
        entity.setWhere_(" where vip_no = '" + mobile + "' ");
        entity.setOrder_(" order by create_time desc ");
        Page<Map<String, Object>> result = iLogisticsBasisService.findPage(entity,pageIndex,pageCount);
        return result;
    }

    @Override
    public String delWithdrawDetail(String withdrawNo, String orderNo) {
        String postResult = "";
        String returnStr = "";
        Map<String,String> postMap = new HashMap<>();
        postMap.put("withdrawNo",withdrawNo);
        postMap.put("orderNo",orderNo);
        WithDrawMoneyMain withDrawForUpdate = withDrawMoneyMainMapper.selectByWithdrawNo(withdrawNo);
        String code = withDrawForUpdate.getCode();
        //如果是F6系统，则帐套名称和组织代码必须传
        Company company = iCompanyInfoService.getCompanyByCode(code);
        String url = company.getUrl() + "/withdrawAudit/deleteWithdrawAuditData";
        if(StringUtil.isNotEmpty(company.getF6AccountSet()) && StringUtil.isNotEmpty(company.getF6OrganizationCode())){
            url += "?accountName=" + company.getF6AccountSet() + "&organizationCode=" + company.getF6OrganizationCode();
        }
        postResult = HttpUtil.post(url,postMap);
        //根据删除结果进行本地主表Update
        if("200".equals(JSON.parseObject(postResult).getString("code"))){
            List<WithdrawMoney> returnList = JSON.parseObject(postResult).getJSONArray("content").toJavaList(WithdrawMoney.class);
            if(null != returnList){
                Double deledDeliveryCollection = 0.0;  //总删除代收
                int deledTotalCount = 0 ;  //删除票数总计
                for(int i=0;i<returnList.size();i++){
                    if("".equals(returnList.get(i).getRemark()) || null == returnList.get(i).getRemark()){
                        deledDeliveryCollection += returnList.get(i).getDeliveryCollection();
                        deledTotalCount ++;
                    }else{
                        //无法删除票据拼装remark无法删除原因;
                        returnStr += "票号:"+returnList.get(i).getOrderNo()+"删除失败,原因:"+returnList.get(i).getRemark()+",";
                    }
                }
                //如果已删除数量和需要更新总数一直,删除本地记录;
                if(deledTotalCount == withDrawForUpdate.getOrderSum()){
                    withDrawMoneyMainMapper.deleteByPrimaryKey(withDrawForUpdate.getWithDrawNo());
                    returnStr = "删除全部记录";
                }else{
                    //如果只是其中几票删除,则进行更新
                    withDrawForUpdate.setOrderSum(withDrawForUpdate.getOrderSum() - deledTotalCount);
                    deledDeliveryCollection = Double.parseDouble(withDrawForUpdate.getDeliveryCollection()) - deledDeliveryCollection;
                    withDrawForUpdate.setDeliveryCollection(deledDeliveryCollection.toString());
                    withDrawMoneyMainMapper.updateByWithDrawNo(withDrawForUpdate);
                }
            }
        }

        return returnStr;
    }

    @Override
    public String findWithdrawMoneyDetail(String withdrawNo,String mobile) {
        WithDrawMoneyMain withDrawForUpdate = withDrawMoneyMainMapper.selectByWithdrawNo(withdrawNo);
        Company company = iCompanyInfoService.getCompanyByCode(withDrawForUpdate.getCode());
        //如果是F6系统，则帐套名称和组织代码必须传
        String url = company.getUrl() + "/withdrawAudit/getWithdrawDataInfo?telphone=" + mobile + "&withdrawNo=" + withdrawNo;
        if(StringUtil.isNotEmpty(company.getF6AccountSet()) && StringUtil.isNotEmpty(company.getF6OrganizationCode())){
            url += "&accountName=" + company.getF6AccountSet() + "&organizationCode=" + company.getF6OrganizationCode();
        }
        return HttpUtil.get(url);
    }

    /**
     * 小程序主页取款信息
     *
     * @param code
     * @param vipNo
     * @return
     */
    @Override
    public List<WithDrawMoneyMain> searchWithDrawForIndex(String code,String vipNo){
        Long begin = System.currentTimeMillis();//开始时间
        WithDrawMoneyMain searchModel = new WithDrawMoneyMain();
        searchModel.setCode(code);
        searchModel.setVipNo(vipNo);
        Long end = System.currentTimeMillis();//结束时间
        System.out.print("首页取款总用时：" + (end - begin) + "毫秒。");
        return withDrawMoneyMainMapper.searchWithDrawForIndex(searchModel);
    }

    @Override
    public ResultModel searchDeliveryCollectionInfo(String code,String telphone,String state,String giveStartDate,
                                                    String giveEndDate,String startDate,String endDate) {
        Company company = iCompanyInfoService.getCompanyByCode(code);
        //如果是F6系统，则帐套名称和组织代码必须传
        String url = null;
        if(StringUtil.isNotEmpty(giveStartDate) && StringUtil.isNotEmpty(giveEndDate)){
            url = company.getUrl() + "/withdrawAudit/searchDeliveryCollectionInfo?telphone=" + telphone +
                    "&state=" + state + "&giveStartDate=" + giveStartDate + "&giveEndDate=" + giveEndDate + "&code=" + code;
        }
        if(StringUtil.isNotEmpty(startDate) && StringUtil.isNotEmpty(endDate)){
            url = company.getUrl() + "/withdrawAudit/searchDeliveryCollectionInfo?telphone=" + telphone +
                    "&state=" + state + "&startDate=" + startDate + "&endDate=" + endDate + "&code=" + code;
        }
        if(StringUtil.isNotEmpty(company.getF6AccountSet()) && StringUtil.isNotEmpty(company.getF6OrganizationCode())){
            url += "&accountName=" + company.getF6AccountSet() + "&organizationCode=" + company.getF6OrganizationCode();
        }
        ResultModel model = JSON.parseObject(HttpUtil.get(url),ResultModel.class);
        if(200 == model.getCode()){
            if("SUCCESS".equals(model.getMsg())){
                Map<String,Object> result = Maps.newHashMap();
                List<Map<String,Object>> list = (List) model.getContent();
                double sum = 0;
                if(CollectionUtils.isNotEmpty(list)){
                    for(Map<String,Object> map : list){
                        sum += Double.parseDouble(map.get("deliveryCollection").toString());
                    }
                }
                result.put("list",list);
                result.put("count",list.size());
                result.put("sum",sum);

                return ResultModel.ok(result);
            }else{
                return ResultModel.error(model.getMsg());
            }
        }else{
            return ResultModel.error(ResultStatus.SERVER_ERROR);
        }
    }


}
